import math


def point_to_line_distance(a, b):
    x1, y1 = a
    (x2, y2), (x3, y3) = b

    px = x3 - x2
    py = y3 - y2
    norm = px * px + py * py

    u = ((x1 - x2) * px + (y1 - y2) * py) / float(norm)

    if u > 1:
        u = 1
    elif u < 0:
        u = 0

    x = x2 + u * px
    y = y2 + u * py

    dx = x - x1
    dy = y - y1

    distance = math.sqrt(dx * dx + dy * dy)
    return distance

def cal_min_distance(bajiao, bbox):
    # bbox_loc = [[bbox[0], bbox[1]], [bbox[0], bbox[2]], [bbox[2], bbox[3]], [bbox[2], bbox[0]]]
    # print(bbox_loc)

    # width = bbox[2] - bbox[0]
    # height = bbox[3] - bbox[1]
    # bbox_loc = [[bbox[0]+0.5*width, bbox[1]], [bbox[0], bbox[1]+0.5*height], [bbox[2]-0.5*width, bbox[3]], [bbox[2], bbox[3]-0.5*height]]
    # print(bbox_loc)

    
    distance = []
    bajiao_x_min = min([x[0] for x in bajiao])
    bajiao_x_max = max([x[0] for x in bajiao])
    bajiao_y_min = min([x[1] for x in bajiao])
    bajiao_y_max = max([x[1] for x in bajiao])
    # 左
    left_dis = bbox[0] - bajiao_x_min
    distance.append(left_dis)
    # 上
    up_dis = bbox[1] - bajiao_y_min
    distance.append(up_dis)
    # 右
    right_dis = bajiao_x_max - bbox[2]
    distance.append(right_dis)
    # 下
    down_dis = bajiao_y_max - bbox[3]
    distance.append(down_dis)

    # bajiao_x = [x[0] for x in bajiao]
    # bajiao_x = list(set(bajiao_x))
    # bajiao_x = sorted(bajiao_x)
    # bajiao_y = [x[1] for x in bajiao]
    # bajiao_y = list(set(bajiao_y))
    # bajiao_y = sorted(bajiao_y)

    # # 左上
    # point = bbox_loc[0]
    # line = [(bajiao_x[0], bajiao_y[1]), (bajiao_x[1], bajiao_y[0])]
    # lu_dis = point_to_line_distance(point, line)
    # distance.append(lu_dis)

    # # 左下
    # point = bbox_loc[1]
    # line = [(bajiao_x[0], bajiao_y[2]), (bajiao_x[1], bajiao_y[3])]
    # ld_dis = point_to_line_distance(point, line)
    # distance.append(ld_dis)

    # # 右上
    # point = bbox_loc[3]
    # line = [(bajiao_x[2], bajiao_y[0]), (bajiao_x[3], bajiao_y[1])]
    # ru_dis = point_to_line_distance(point, line)
    # distance.append(ru_dis)

    # # 右下
    # point = bbox_loc[2]
    # line = [(bajiao_x[2], bajiao_y[3]), (bajiao_x[3], bajiao_y[2])]
    # rd_dis = point_to_line_distance(point, line)
    # distance.append(rd_dis)

    # print(distance)
    # img = np.ones((200,200), dtype=np.uint8) * 255
    # bajiao_line = np.array(bajiao, np.int32)
    # cv2.polylines(img, [bajiao_line], True, (50, 0, 200), 2)
    # bbox_line = np.array(bbox_loc)
    # cv2.polylines(img, [bbox_line], True, (0, 200, 0), 2)
    # cv2.imshow("White Image", img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    return min(distance)

# bajiao = [[0, 20], [0, 80], [20, 100], [80, 100], [100, 80], [100, 20], [80, 0], [20, 0]]
# bbox = [12, 12, 30, 30]

# min_distance = cal_min_distance(bajiao, bbox)
# print(min_distance)
